# Create your views here.
from django.shortcuts import get_object_or_404, render_to_response
from models import Entry, Category
from django.contrib.syndication.feeds import Feed
from django.utils.feedgenerator import Atom1Feed


def entries_index(request):
    return render_to_response('zblog/entry_index.html', {'entry_list':Entry.objects.all()})

def entry_detail(request, year, month, day, slug):
    import datetime, time
    date_stamp = time.strptime(year+month+day, "%Y%b%d")
    pub_date = datetime.date(*date_stamp[:3])
    entry = get_object_or_404(Entry, pub_date__year = year,
                                        pub_date__month = month,
                                        pub_date__day = day,
                                        slug=slug)
    return ender_to_response('zblog/entry_detail.html', { 'entry': entry })


def entry_by_category(request, slug):
    category = get_object_or_404(Category, slug=slug)
    return render_to_response('zblog/entry_by_category.html',
                              { 'object_list': category.entry_set.all(),
                               'category': category })

def entry_by_id(request, id):
    id = int(id)
    entry = get_object_or_404(Entry, id=id)
    return render_to_response('zblog/entry_detail.html', { 'object': entry })

def latest_ten_entry(request):
    return render_to_response('zblog/entry_latest.html',
                              { 'entry_latest_list': Entry.objects.filter(status=Entry.LIVE_STATUS)[:8],})

    
def search(request):
    query = request.GET.get('q', '')
    results = []
    if query:
        results = Entry.objects.filter(body__icontains=query) | Entry.objects.filter(title__icontains=query)
    return render_to_response('zblog/search.html',
                              { 'query': query, 'results': results })
    
class RssLatestEntries(Feed):
    title = "Haibo's Blog"
    link = "/archive/"
    description = "Feeds: Haibo's latest stuff"

    def items(self):
        return Entry.objects.order_by('-pub_date')[:10]

class AtomLatestEntries(RssLatestEntries):
    feed_type = Atom1Feed
